<?php
namespace App\Helper;
use Illuminate\Support\Facades\File;
use function EasyWeChat\Kernel\Support\get_client_ip;
use Hyperf\Utils\ApplicationContext;
use Psr\Http\Message\ServerRequestInterface;
use Illuminate\Support\Facades\URL;

class Utils
{
    public static function createFileName()
    {
        $name = md5(date('Y/m/d-H:i:s-') . uniqid());
        return $name;
    }

    public static function replaceContentImg($content){
        $content = preg_replace_callback("/<[img|IMG].*?src=[\'|\"](.*?(?:[\.jpg|\.jpeg|\.png|\.gif|\.bmp]))[\'|\"].*?[\/]?>/",function ($r) {
            return str_replace($r[1], config('common.image_prefix').$r[1],$r[0]);
        },$content);
        return $content;
    }

    public static function stripContentImgPrefix($content){
        $content = preg_replace_callback("/<[img|IMG].*?src=[\'|\"](.*?(?:[\.jpg|\.jpeg|\.png|\.gif|\.bmp]))[\'|\"].*?[\/]?>/",function ($r) {
            return str_replace(config('common.image_prefix'),'',$r[0]);
        },$content);
        return $content;
    }

    public static function random($length, $numeric = 0) {
        $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
        $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
        if ($numeric) {
            $hash = '';
        } else {
            $hash = chr(rand(1, 26) + rand(0, 1) * 32 + 64);
            $length--;
        }
        $max = strlen($seed) - 1;
        for ($i = 0; $i < $length; $i++) {
            $hash .= $seed{mt_rand(0, $max)};
        }
        return $hash;
    }

    public static function replacePhone($phone){
        return substr_replace($phone, '****', 3, 4);
    }

    public static function container()
    {
        return ApplicationContext::getContainer();
    }

    public static function url($url, $params = [], $tag='&')
    {
        $constr = '?';
        if((strpos($url,'?') !== false)){
            $constr = '&';
        }
        $str = '';
        foreach ($params as $k=>$v) {
            if (empty($str)){
                $str = $constr . $k . '=' .$v;
            }else{
                $str .= $tag . $k . '=' .$v;
            }
        }
        if (empty($url)){
            return '';
        }
        if ($url[0]=='/'){
            return $url.$str;
        }elseif((strpos($url,'http://') !== false)||(strpos($url,'https://') !== false)){
            return $url.$str;
        }
        else{
            return '/'.$url.$str;
        }
    }
    public static function getClientIp()
    {
        return get_client_ip();
    }

    public static function ip(){
        $res = request()->getServerParams();
        if(isset($res['http_client_ip'])){
            return $res['http_client_ip'];
        }elseif(isset($res['http_x_real_ip'])){
            return $res['http_x_real_ip'];
        }elseif(isset($res['http_x_forwarded_for'])){
            //部分CDN会获取多层代理IP，所以转成数组取第一个值
            $arr = explode(',',$res['http_x_forwarded_for']);
            return $arr[0];
        }else{
            return $res['remote_addr'];
        }
    }

    public static function createPoster($config=[],$path='',$filename=""){
        if(empty($filename)) header("content-type: image/png");
        $imageDefault = [
            'left'=>0,
            'top'=>0,
            'right'=>0,
            'bottom'=>0,
            'width'=>100,
            'height'=>100,
            'opacity'=>100
        ];
        $textDefault = [
            'text'=>'',
            'left'=>0,
            'top'=>0,
            'fontSize'=>32,       //字号
            'fontColor'=>'255,255,255', //字体颜色
            'angle'=>0,
        ];
        $background = $config['background'];//海报最底层得背景
        //背景方法
        $backgroundInfo = getimagesize($background);
        $backgroundFun = 'imagecreatefrom'.image_type_to_extension($backgroundInfo[2], false);
        $background = $backgroundFun($background);
        $backgroundWidth = imagesx($background);  //背景宽度
        $backgroundHeight = imagesy($background);  //背景高度
        $imageRes = imageCreatetruecolor($backgroundWidth,$backgroundHeight);
        $color = imagecolorallocate($imageRes, 0, 0, 0);
        imagefill($imageRes, 0, 0, $color);
        // imageColorTransparent($imageRes, $color);  //颜色透明
        imagecopyresampled($imageRes,$background,0,0,0,0,imagesx($background),imagesy($background),imagesx($background),imagesy($background));
        //处理了图片
        if(!empty($config['image'])){
            foreach ($config['image'] as $key => $val) {
                $val = array_merge($imageDefault,$val);
                $info = getimagesize($val['url']);
                $extension = image_type_to_extension($info[2], false);
                $function = 'imagecreatefrom'.image_type_to_extension($info[2], false);
                if($val['stream']){   //如果传的是字符串图像流
                    $info = getimagesizefromstring($val['url']);
                    $function = 'imagecreatefromstring';
                }
                $res = $function($val['url']);
                $resWidth = $info[0];
                $resHeight = $info[1];
                //建立画板 ，缩放图片至指定尺寸
                $canvas=imagecreatetruecolor($val['width'], $val['height']);
                if($extension=='png' || $extension=='gif'){
                    $color = imagecolorallocate($canvas,255,255,255);
                    imagecolortransparent($canvas,$color);
                }
                imagefill($canvas, 0, 0, $color);
                //关键函数，参数（目标资源，源，目标资源的开始坐标x,y, 源资源的开始坐标x,y,目标资源的宽高w,h,源资源的宽高w,h）
                imagecopyresampled($canvas, $res, 0, 0, 0, 0, $val['width'], $val['height'],$resWidth,$resHeight);
                $val['left'] = $val['left']<0?$backgroundWidth- abs($val['left']) - $val['width']:$val['left'];
                $val['top'] = $val['top']<0?$backgroundHeight- abs($val['top']) - $val['height']:$val['top'];
                //放置图像
                imagecopymerge($imageRes,$canvas, $val['left'],$val['top'],$val['right'],$val['bottom'],$val['width'],$val['height'],$val['opacity']);//左，上，右，下，宽度，高度，透明度
            }
        }
        //处理文字
        if(!empty($config['text'])){
            foreach ($config['text'] as $key => $val) {
                $val = array_merge($textDefault,$val);
                list($R,$G,$B) = explode(',', $val['fontColor']);
                $fontColor = imagecolorallocate($imageRes, $R, $G, $B);
                $val['left'] = $val['left']<0?$backgroundWidth- abs($val['left']):$val['left'];
                $val['top'] = $val['top']<0?$backgroundHeight- abs($val['top']):$val['top'];
                imagettftext($imageRes,$val['fontSize'],$val['angle'],$val['left'],$val['top'],$fontColor,$val['fontPath'],$val['text']);
            }
        }
        //生成图片
        if(!empty($path) && !empty($filename)){
            is_dir($path) or mkdir($path,0777,true);
            //\Illuminate\Support\Facades\File::isDirectory($path) or \Illuminate\Support\Facades\File::makeDirectory($path, 0777, true, true);
            $res = imagejpeg ($imageRes,$path.'/'.$filename,90); //保存到本地
            imagedestroy($imageRes);
            if(!$res) return false;
            return $filename;
        }else{
            imagejpeg ($imageRes);     //在浏览器上显示
            imagedestroy($imageRes);
        }
    }

    public static function hex2rgb($hexColor) {
        $color = str_replace('#', '', $hexColor);
        if (strlen($color) > 3) {
            $rgb = array(
                'r' => hexdec(substr($color, 0, 2)),
                'g' => hexdec(substr($color, 2, 2)),
                'b' => hexdec(substr($color, 4, 2))
            );
        } else {
            $color = $hexColor;
            $r = substr($color, 0, 1) . substr($color, 0, 1);
            $g = substr($color, 1, 1) . substr($color, 1, 1);
            $b = substr($color, 2, 1) . substr($color, 2, 1);
            $rgb = [
                'r' => hexdec($r),
                'g' => hexdec($g),
                'b' => hexdec($b)
            ];
        }
        return $rgb;
    }

    public static function read_csv($csv_file = '', $lines = 0, $offset = 0){
        if (!$fp = fopen($csv_file, 'r')) {
            return false;
        }
        $i=0;
        $arr=[];
        while($data = fgetcsv($fp)){
            if($i < $offset && $offset){
                $i++;
                continue;
            }
            //大于读取行数则退出
            if($i > $lines && $lines){
                break;
            }
            foreach ($data as $key => $value) {
                $content = iconv("gbk","utf-8//IGNORE",$value);//转化编码
                $arr[$i][$key] = $content;//至于如何处理这个结果，需要根据实际情况而定
            }
            $i++;

        }
        return $arr;
    }

    public static function export_csv($data = [], $header_data = [], $file_name = ''){
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename='.$file_name);
        header('Cache-Control: max-age=0');
        $fp = fopen('php://output', 'a');
        if (!empty($header_data)) {
            foreach ($header_data as $key => $value) {
                $header_data[$key] = iconv('utf-8', 'gbk', $value);
            }
            fputcsv($fp, $header_data);
        }
        $num = 0;
        //每隔$limit行，刷新一下输出buffer，不要太大，也不要太小
        $limit = 100000;
        //逐行取出数据，不浪费内存
        $count = count($data);
        if ($count > 0) {
            for ($i = 0; $i < $count; $i++) {
                $num++;
                //刷新一下输出buffer，防止由于数据过多造成问题
                if ($limit == $num) {
                    ob_flush();
                    flush();
                    $num = 0;
                }
                $row = $data[$i];
                foreach ($row as $key => $value) {
                    $row[$key] = iconv('utf-8', 'gbk', $value);
                }
                fputcsv($fp, $row);
            }
        }
        fclose($fp);
    }

    public static function export_csv_file($data = [], $header_data = [], $file_name = ''){
        $newname = Utils::createFileName().'.csv';
        $dir = '/uploads/'.date('Ym').'/'.date('d').'/';
        $folder = BASE_PATH.'/public'.$dir;
        if (!is_dir($folder)) {
            mkdir($folder, 0777, true);
        }
        $fp = fopen($folder.$newname,'w+');
        if (!empty($header_data)) {
            foreach ($header_data as $key => $value) {
                $header_data[$key] = iconv('utf-8', 'gbk', $value);
            }
            fputcsv($fp, $header_data);
        }
        $num = 0;
        //每隔$limit行，刷新一下输出buffer，不要太大，也不要太小
        $limit = 100000;
        //逐行取出数据，不浪费内存
        $count = count($data);
        if ($count > 0) {
            for ($i = 0; $i < $count; $i++) {
                $num++;
                //刷新一下输出buffer，防止由于数据过多造成问题
                if ($limit == $num) {
                    ob_flush();
                    flush();
                    $num = 0;
                }
                $row = $data[$i];
                foreach ($row as $key => $value) {
                    $row[$key] = iconv('utf-8', 'gbk', $value);
                }
                fputcsv($fp, $row);
            }
        }
        fclose($fp);
        return $dir.$newname;
    }

    public static function stringPref($string){
        if(!preg_match("/([\x81-\xfe][\x40-\xfe])/", $string, $match)){
            return false;
        }
        if(preg_match('/(.*?)[正确错误]$/',$string)){
           return $string;
        }
        $replace_arr=['判断题','断题','多选题','选题','单选题','选题','》','练习模式','背题模式'];
        foreach ($replace_arr as $v){
            $string = str_replace($v,'',$string);
        }
        $preg1='/^[0-9a-zA-Z][\x81-\xfe][\x40-\xfe][\x81-\xfe\x40-\xfe].*?/';
        $preg2='/^[0-9a-zA-Z][:,].*?/';
        preg_match($preg1,$string,$arr);
        if(!empty($arr)){
            $string = preg_replace($preg1,'',$string);
        }
        preg_match($preg2,$string,$arr);
        if(!empty($arr)){
            $string = preg_replace($preg2,'',$string);
        }
        $string = preg_replace('/。$/','',$string);
        return $string;
    }

    public static  function createNonceStr($length = 32) {
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    public static function createActiveCode() {
        $code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $rand = $code[rand(0,25)]
            .strtoupper(dechex(date('m')))
            .date('d').substr(time(),-5)
            .substr(microtime(),2,5)
            .sprintf('%02d',rand(0,99));
        for(
            $a = md5( $rand, true ),
            $s = '0123456789ABCDEFGHIJKLMNOPQRSTUV',
            $d = '',
            $f = 0;
            $f < 8;
            $g = ord( $a[ $f ] ),
            $d .= $s[ ( $g ^ ord( $a[ $f + 8 ] ) ) - $g & 0x1F ],
            $f++
        );
        return $d;
    }

    public static function returnSquarePoint($lng, $lat,$distance = 5)
    {
        $earthdata=6371;//地球半径，平均半径为6371km
        $dlng =  2 * asin(sin($distance / (2 * $earthdata)) / cos(deg2rad($lat)));
        $dlng = rad2deg($dlng);
        $dlat = $distance/$earthdata;
        $dlat = rad2deg($dlat);
        $arr=[
            'left_top'=>['lat'=>$lat + $dlat,'lng'=>$lng-$dlng],
            'right_top'=>['lat'=>$lat + $dlat, 'lng'=>$lng + $dlng],
            'left_bottom'=>['lat'=>$lat - $dlat, 'lng'=>$lng - $dlng],
            'right_bottom'=>['lat'=>$lat - $dlat, 'lng'=>$lng + $dlng]
        ];
        return $arr;
    }

    public static function randFloat($min = 0, $max = 1) {
        return $min + mt_rand() / mt_getrandmax() * ($max - $min);
    }

    public static function uuid($prefix=''){
        $chars = md5(uniqid(mt_rand(), true));
        $uuid = substr ( $chars, 0, 8 ) . '-'
            . substr ( $chars, 8, 4 ) . '-'
            . substr ( $chars, 12, 4 ) . '-'
            . substr ( $chars, 16, 4 ) . '-'
            . substr ( $chars, 20, 12 );
        return $prefix.$uuid ;
    }

    public static function generateSign($params,$secret){

        $tmps = array();
        foreach ($params as $k => $v) {
            $tmps[] = $k . $v;
        }
        $string = $secret . implode('', $tmps);
        return strtoupper(md5($string));
    }

}
